package com.citcc.api.netty.server;

import com.citcc.api.netty.EchargeConstants;
import com.citcc.api.netty.bean.ConsuMessage;
import com.citcc.api.netty.utils.HexUtil;
import com.citcc.business.bean.CdzGun;
import com.citcc.business.bean.CdzIndent;
import com.citcc.business.bean.UserOrderEntity;
import com.citcc.business.bean.UserOrderEntityExample;
import com.citcc.business.service.CdzGunService;
import com.citcc.business.service.CdzIndentService;
import com.citcc.business.service.CdzStakeService;
import com.citcc.business.service.ScanCodeService;
import com.citcc.business.util.CollectionUtil;
import com.citcc.framework.sms.JsonResult;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.UUID;

import javax.annotation.Generated;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.buffer.ChannelBuffers;
import org.jboss.netty.channel.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * @author liyachong
 * @date 2019/4/5
 * @time 13:41
 */
@SuppressWarnings("all")
@Component
public class ServerToClient {

	private Logger log = LoggerFactory.getLogger(ServerToClient.class);
	private static List<String> list = Arrays.asList("0","1","2","3");
	// 扩展
	public static ScanCodeService scanCodeService;
	
	//订单业务
    public static CdzIndentService cdzIndentService;

	/**
	 * 下发启动充电指令
	 * 
	 * @param msg
	 * @param
	 * @return 1 开启充电成功 ，2 充电桩不在线
	 */
	public int startCmd(ConsuMessage msg) {
		String deviceNo = msg.getDeviceNo()+"";
		String source = msg.getSource()+"";
		String phone = msg.getPhone();
		long time = msg.getTime();
		long money = msg.getMoney();
		long dl = msg.getDl();
		String mode = msg.getMode();
		String id = msg.getId();
		if(StringUtils.isEmpty(id)){
        	log.warn("不存在订单------------------");
        	return 10;
        }
		log.info("终端号=="+deviceNo+"-->枪号="+source+"-->手机号:"+phone+"-->充电时间:"+time+"-->充电模式:"+mode+"-->充电金额:"+money+"-->充电电量:"+dl+"-->订单id:"+id);
        if(!list.contains(mode)){
        	log.warn("充电模式不合法------------------");
        	return 10;
        }
        if("1".equals(mode) && StringUtils.isEmpty(money)){
        	log.warn("充电模式为1时，充电金额不能为空------------------");
        	return 10;
        }
        if("2".equals(mode) && StringUtils.isEmpty(time)){
        	log.warn("充电模式为2时，充电时间不能为空------------------");
        	return 10;
        }
        if("3".equals(mode) && StringUtils.isEmpty(dl)){
        	log.warn("充电模式为3时，充电电量不能为空------------------");
        	return 10;
        }
		Channel channel = ChannelMap.getChannelByName(msg.getDeviceNo() + "");
		if(channel==null){
			log.error("监控平台下发开启充电指令失败=========设备不在线==" + msg.getDeviceNo());
			return 6;
		}
		boolean res = channel.isConnected();
		log.warn("监控平台下发开启充电指令=========设备号==" + msg.getDeviceNo()+"----状态:"+res);
		if (channel.isConnected()) {
			if (msg.getDeviceNo() == 0 || msg.getSource() == 0) {
				log.error("下发开启充电指令时终端号:" + msg.getDeviceNo() + "-->枪号:" + msg.getSource() + "-->都不能为空");
				return 3;
			}
			long l = msg.getDeviceNo();
			String hex = Long.toHexString(l);
			String hex8 = HexUtil.befor0(hex, 8);
			String realHex = HexUtil.hexHighLow(hex8);
			log.info("下发开启指令时---终端号:"+l+"-->枪号:"+msg.getSource()+"-->终端号高低位换后的值:"+realHex);
			// 判断该终端号+枪号 是否可用
			CdzGun cdzGun = scanCodeService.checkCdzGun(msg.getSource() + "", msg.getDeviceNo() + "");
			//链接成功 未充电状态
			if (cdzGun != null && EchargeConstants.NOT_CHARGING_STATUS.equals(cdzGun.getStatus())) {
				//TODO 判断是否存在该支付成功的订单
				/*UserOrderEntityExample example = new UserOrderEntityExample();
		    	UserOrderEntityExample.Criteria criteria = example.createCriteria();
		    	criteria.andDelFlagEqualTo("0");
		    	criteria.andChargeStateEqualTo("1");//未充电
		    	criteria.andStakeCodeEqualTo(msg.getDeviceNo()+"");
		    	criteria.andGunCodeEqualTo(msg.getSource()+"");
		    	criteria.andPayStateEqualTo("2");//支付成功
		    	criteria.andUserPhoneEqualTo(phone);
		    	example.setOrderByClause("CREATE_TIME DESC");
		    	UserOrderEntity e = scanCodeService.getUserOrderEntity(example);*/
				UserOrderEntity e = scanCodeService.getCdOrder(id);
				if(e==null || !("0".equals(e.getDelFlag())) || !("1".equals(e.getChargeState()))){
					log.error("下发开启充电指令时终端号:" + msg.getDeviceNo() + "-->枪号:" + msg.getSource() + "-->手机号"+msg.getPhone()+"-->没有查询到未充电的有效订单");
					return 5;
				}
				BigDecimal dj = e.getPayNumber();
				if(dj==null){
					dj = BigDecimal.ZERO;
				}
				dj = dj.setScale(2, BigDecimal.ROUND_HALF_UP);
				long m = dj.multiply(new BigDecimal(100)).longValue();
				ChannelBuffer body = ChannelBuffers.buffer(50);
				body.writeShort(0x3700);
				body.writeBytes(HexUtil.hexStringToByte(realHex));// 终端号
				body.writeByte(EchargeConstants.START_CD_C);
				int s = msg.getSource();
				String frame = Integer.toHexString(s+16);
				if ("10".equals(frame)) {
					body.writeByte(0x00);// 1帧来源+枪号
				} else if ("11".equals(frame)) {
					body.writeByte(0x01);// 1帧来源+枪号
				} else if ("12".equals(frame)) {
					body.writeByte(0x02);// 1帧来源+枪号
				} else if ("13".equals(frame)) {
					body.writeByte(0x03);// 1帧来源+枪号
				} else if ("14".equals(frame)) {
					body.writeByte(0x04);// 1帧来源+枪号
				}
				body.writeByte(0x00);// 请求
				body.writeByte(0x01);// 启动
				/*
				 * body.writeInt(0x31373038);//流水号 body.writeInt(0x31373136);
				 * body.writeInt(0x32393531); body.writeInt(0x30313831);
				 * body.writeInt(0x00000000);
				 */
				body.writeBytes(HexUtil.getBytesWithLengthAfter(20, msg.getPhone().getBytes()));
				//余额
				if("0".equals(msg.getMode())){//自动充电
					//long m = 100000l;
					String h = Long.toHexString(m);
					String ss = HexUtil.befor0(h, 8);
					String hl = HexUtil.hexHighLow(ss);
					body.writeBytes(HexUtil.hexStringToByte(hl));//单位分
				}else if("1".equals(msg.getMode())){//金额模式  单位分
					String h = Long.toHexString(money);
					String ss = HexUtil.befor0(h, 8);
					String hl = HexUtil.hexHighLow(ss);
					body.writeBytes(HexUtil.hexStringToByte(hl));//单位分
					
				}else if("2".equals(msg.getMode())){//时间模式
					//long m = 100000l;
					String h = Long.toHexString(m);
					String ss = HexUtil.befor0(h, 8);
					String hl = HexUtil.hexHighLow(ss);
					body.writeBytes(HexUtil.hexStringToByte(hl));//单位分
				}else if("3".equals(msg.getMode())){//电量模式
					//long m = 100000l;//1000元
					String h = Long.toHexString(m);
					String ss = HexUtil.befor0(h, 8);
					String hl = HexUtil.hexHighLow(ss);
					body.writeBytes(HexUtil.hexStringToByte(hl));//单位分
				}

				
				body.writeInt(0x12345678);// 后台流水号
				
				// 充电模式 0.自动充电 1.金额模式 2.时间模式 3电量模式
				// 充电参数  100秒
				if("0".equals(msg.getMode())){//自动充电
					body.writeInt(0x00000000);
					body.writeInt(0x00000000);
				}else if("1".equals(msg.getMode())){//金额模式  单位分
					body.writeInt(0x01000000);
					//body.writeInt(0x64000000);//100分钱
					log.info("开启充电时充电金额:"+money+" 分");
					String h = Long.toHexString(money);
					String ss = HexUtil.befor0(h, 8);
					String hl = HexUtil.hexHighLow(ss);
					body.writeBytes(HexUtil.hexStringToByte(hl));//单位分
				}else if("2".equals(msg.getMode())){//时间模式
					String h = Long.toHexString(time);
					String ss = HexUtil.befor0(h, 8);
					String hl = HexUtil.hexHighLow(ss);
					body.writeInt(0x02000000);
					body.writeBytes(HexUtil.hexStringToByte(hl));//单位秒
				}else if("3".equals(msg.getMode())){//电量模式
					String h = Long.toHexString(dl);
					String ss = HexUtil.befor0(h, 8);
					String hl = HexUtil.hexHighLow(ss);
					body.writeInt(0x03000000);
					body.writeBytes(HexUtil.hexStringToByte(hl));//0.01KW.H
				}
				body.writeInt(0x00000000);// 固定
				msg.setMsgBody(body);
				channel.write(msg);
				log.error("监控平台下发开启充电指令成功=========设备号==" + msg.getDeviceNo());
				return 200;
			} else {
				log.error("下发开启充电指令时终端号:" + msg.getDeviceNo() + "-->枪号:" + msg.getSource() + "-->该枪不在空闲转态或不存在该枪的信息");
				return 4;
			}
		} else {
			log.error("监控平台下发开启充电指令失败=========设备不在线==" + msg.getDeviceNo());
			return 2;// 不在线
		}
	}

	/**
	 * 下发启动停止指令
	 * 
	 * @param msg
	 * @param
	 * @return 1 成功 ，2 充电桩不在线
	 */
	public int stopCmd(ConsuMessage msg) {
		Channel c = ChannelMap.getChannelByName(msg.getDeviceNo() + "");
		if(c==null){
			log.info("监控平台下发停止充电指令失败=========设备不在线==" + msg.getDeviceNo());
			return 6;
		}
		Channel channel = (Channel) ChannelMap.getChannelByName(msg.getDeviceNo() + "");
		if (channel.isConnected()) {
			if (StringUtils.isEmpty(msg.getDeviceNo()) || StringUtils.isEmpty(msg.getSource())) {
				log.error("下发停止充电指令时终端号:" + msg.getDeviceNo() + "-->枪号:" + msg.getSource() + "-->都不能为空");
				return 3;
			}
			long l = msg.getDeviceNo();
			String hex = Long.toHexString(l);
			String hex8 = HexUtil.befor0(hex, 8);
			String realHex = HexUtil.hexHighLow(hex8);
			log.info("下发关闭指令时---终端号:"+l+"-->枪号:"+msg.getSource()+"-->终端号高低位换后的值:"+realHex);
			CdzGun cdzGun = scanCodeService.checkCdzGun(msg.getSource() + "", msg.getDeviceNo() + "");
			//链接成功 充电中状态
			if (cdzGun != null && EchargeConstants.CHARGING_STATUS.equals(cdzGun.getStatus())) {
				ChannelBuffer body = ChannelBuffers.buffer(50);
				body.writeShort(0x3700);
				body.writeBytes(HexUtil.hexStringToByte(realHex));// 终端号
				body.writeByte(EchargeConstants.START_CD_C);
				int s = msg.getSource();
				String frame = Integer.toHexString(s+16);
				if ("10".equals(frame)) {
					body.writeByte(0x00);// 1帧来源+枪号
				} else if ("11".equals(frame)) {
					body.writeByte(0x01);// 1帧来源+枪号
				} else if ("12".equals(frame)) {
					body.writeByte(0x02);// 1帧来源+枪号
				} else if ("13".equals(frame)) {
					body.writeByte(0x03);// 1帧来源+枪号
				}else if ("14".equals(frame)) {
					body.writeByte(0x04);// 1帧来源+枪号
				}
				body.writeByte(0x00);// 请求
				body.writeByte(0x02);// 停止
				/*
				 * body.writeInt(0x31373038);//流水号 body.writeInt(0x31373136);
				 * body.writeInt(0x32393531); body.writeInt(0x30313831);
				 * body.writeInt(0x00000000);
				 */
				body.writeBytes(HexUtil.getBytesWithLengthAfter(20, "17803875207".getBytes()));
				body.writeInt(0xE8030000);// 余额
				body.writeInt(0x12345678);// 后台流水号
				body.writeInt(0x02000000);// 充电模式
				body.writeInt(0x00000000);// 充电参数
				body.writeInt(0x00000000);// 固定
				msg.setMsgBody(body);
				channel.write(msg);
				log.info("监控平台下发停止充电指令成功=========设备号==" + msg.getDeviceNo());
				return 200;
			} else {
				log.error("下发停止充电指令时终端号:" + msg.getDeviceNo() + "-->枪号:" + msg.getSource() + "-->该枪不在充电中转态或不存在该枪的信息");
				return 4;
			}
		} else {
			log.info("监控平台下发停止充电指令失败=========设备不在线==" + msg.getDeviceNo());
			return 2;// 不在线
		}
	}
	
	 public Date afterHour(Date curDate,int h){
	    	Calendar ca=Calendar.getInstance();
	    	ca.setTime(curDate);
	    	ca.add(Calendar.HOUR_OF_DAY, h);
	    	return ca.getTime();
	    }

	public static void main(String[] args) {
		String s = Integer.toHexString(100000);
		System.out.println(s);
		String ss = HexUtil.befor0(s, 8);
		String sss = HexUtil.hexHighLow(ss);
		int i = Integer.valueOf(sss, 16);
		System.out.println(i);
	}

}
